package com.hzlx.web;

import com.alibaba.fastjson2.JSON;
import com.hzlx.service.ProductService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.*;
import org.springframework.web.bind.annotation.*;
import com.hzlx.dto.*;
import org.springframework.web.client.RestTemplate;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@Slf4j
public class ProductController {
    @Resource ProductService productService;
    @Resource
    RestTemplate restTemplate;
    @PostMapping("/api/product")
    @ResponseStatus(HttpStatus.CREATED)
    public void create(@RequestBody ProductRequest productRequest){
        productService.create(productRequest);
        log.info("产品{}创建成功",productRequest.getName());
    }
    @GetMapping("/api/product")
    @ResponseStatus(HttpStatus.OK)
    public ResultDto<List<ProductResponse>> findAll(){
        List<ProductResponse> list = productService.findAll();
        // 远程调用查库存？
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        List<Map<String,Object>> skus = list.stream().map(resp-> resp.getSku()).collect(Collectors.toList());
        HttpEntity entity = new HttpEntity(skus, headers);
        ParameterizedTypeReference<ResultDto<List<InventoryResponse>>> pt = new ParameterizedTypeReference<>(){};
        ResponseEntity<ResultDto<List<InventoryResponse>>> result =
                restTemplate.exchange("http://inventory-service/api/inventory/isInStock",
                        HttpMethod.POST,
                        entity,
                        pt);
        if(result.getStatusCode().is2xxSuccessful() && result.getBody().getCode().equals("ok")) {
            List<InventoryResponse> inventoryResponses = result.getBody().getData();
            list.stream().forEach(product->{
                String sku = JSON.toJSONString(product.getSku());
                Integer stock = inventoryResponses.stream()
                        .filter(inventory -> inventory.getSku().equals(sku))
                        .map(inventory -> inventory.getQuantity())
                        .findFirst().orElseGet(()->0);
                product.setStock(stock);
            });
        }
        return ResultDto.<List<ProductResponse>>builder()
                .code("ok")
                .data(list)
                .build();
    }
}
